package com.ptmall.app.net;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.ptmall.app.App;
import com.ptmall.app.BuildConfig;
import com.ptmall.app.MainActivity;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.net.base.BaseBean;
import com.ptmall.app.net.base.Request;
import com.ptmall.app.net.http.NetworkInterceptor;
import com.ptmall.app.net.http.NetworkResponseInterceptor;
import com.ptmall.app.net.http.ResponseConvertFactory;
import com.ptmall.app.utils.SharedPreferenceUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/3/8.
 */

public class HttpMethods {

    public static final String BASE_SITE = BuildConfig.HOST;//配置的地方 在config.gradle内

    public static final String BASE_URL = BASE_SITE + "/api/";

    public static final String BASEIMG_URL = BASE_SITE + "/";
    Gson gson = new Gson();

    //基本参数配置
    public static final String KEY_TIMESTAP = "TIMESTAMP";
    public static final String KEY_DEVICE = "device";
    public static final String DEVICE_VALUE = "app";
    public static final String KEY_ID = "token";
    public static String MEMBERID = "";


    private static final int DEFAULT_TIMEOUT = 10;

    private static Retrofit mRetrofit;


    /**
     * 构造函数里 创建网络请求对象
     */
    private HttpMethods() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
//        builder.addInterceptor(new AppHttpInterceptor());//aplication拦截器
        builder.addNetworkInterceptor(new NetworkInterceptor());//网络拦截器
        builder.addInterceptor(new NetworkResponseInterceptor());//接口请求拦截器

        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(ResponseConvertFactory.create())
//                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();

    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final HttpMethods INSTANCE = new HttpMethods();
    }


    public static synchronized HttpMethods getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 获取网络访问请求对象
     *
     * @return
     */
    public Retrofit getRetrofit() {

        return mRetrofit;
    }

    private class AppHttpInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            okhttp3.Request request = chain.request();
            Response response = chain.proceed(request);
            return response;
        }
    }

    /**
     * 根据 ?extends BaseBean来获取请求体对象
     *
     * @param param
     * @return
     */
    public Request getRequest(BaseBean param) {
        //当前登录者信息
//        Account loginAccount = App.getInstance().getAccount();
//        param.setGuid(loginAccount==null?"":loginAccount.getAccessToken());
//        param.setTIMESTAMP(String.valueOf(System.currentTimeMillis() / 1000));
//        param.setDevice(DEVICE_VALUE);

        //获取json格式 字符串 用于 fromJson Map
        String arg = gson.toJson(param);

        //重新排序用
        TreeMap<String, Object> map = gson.fromJson(arg, TreeMap.class);

        //如果Value中有非String （比如特殊对象Object等）对象 则需要进行转成json格式字符串 防止出现toString 时 key=vaule的格式数据
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof String) {
                map.put(entry.getKey(), entry.getValue());
            } else {
                map.put(entry.getKey(), gson.toJson(entry.getValue()).toString());
            }
        }
        String sign = arg;
        Request request = new Request(arg, sign);
        request.map = map;
        arg = gson.toJson(map).toString();
        if (BuildConfig.DEBUG) {
            Log.d("tag", "arg=" + arg);
        }
        return request;
    }

    /**
     * 根据keys values 获取请求体对象
     *
     * @param keys
     * @param values
     * @return
     */
    public Request getRequest(String[] keys, String[] values) {

        //排序用map
        TreeMap<String, Object> map = new TreeMap();
        if (keys != null && values != null && keys.length == values.length && keys.length > 0) {
            int count = keys.length;
            for (int i = 0; i < count; i++) {
                if (null != keys[i] && null != values[i]) {
                    map.put(keys[i], values[i]);
                }
            }
        }
        map.put(KEY_ID, MEMBERID);
        long time = System.currentTimeMillis() / 1000;
        map.put(KEY_TIMESTAP, String.valueOf(time));

        map.put(KEY_DEVICE, DEVICE_VALUE);

        //如果Value中有非String （比如特殊对象Object等）对象 则需要进行转成json格式字符串 防止出现toString 时 key=vaule的格式数据
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof String) {
                map.put(entry.getKey(), entry.getValue());
            } else {
                map.put(entry.getKey(), gson.toJson(entry.getValue()).toString());
            }
        }
//        String argBase = getBase64(map);
        String arg = gson.toJson(map).toString();
        String sign = arg;
//        map.put(KEY_SIGN, argBase);
        if (BuildConfig.DEBUG) {
            Log.d("tag", "arg=" + arg);
        }
        Request request = new Request(arg, sign);
        request.map = map;
        return request;
    }

    /**
     * @param paraMap
     * @return
     */
    public Request getRequest(Map paraMap) {

        //排序用map
        TreeMap<String, Object> map;
        if (null != paraMap) {
            map = new TreeMap(paraMap);
        } else {
            map = new TreeMap<>();
        }
        long time = System.currentTimeMillis() / 1000;
        map.put(KEY_TIMESTAP, String.valueOf(time));

        map.put(KEY_DEVICE, DEVICE_VALUE);

        //如果Value中有非String （比如特殊对象Object等）对象 则需要进行转成json格式字符串 防止出现toString 时 key=vaule的格式数据
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof String) {
                map.put(entry.getKey(), entry.getValue());
            } else {
                map.put(entry.getKey(), gson.toJson(entry.getValue()).toString());
            }
        }
        map.put(KEY_ID, MEMBERID);
        String argBase = getBase64(map);
        String arg = gson.toJson(map).toString();
        String sign = arg;
//        map.put(KEY_SIGN, argBase);
        map.put("appid", "1002");
        map.put("appkey", "dedSEr85sSkeld36DEs");
        if (BuildConfig.DEBUG) {
            Log.d("tag", "arg=" + arg);
        }
        Request request = new Request(arg, sign);
        request.map = map;
        return request;
    }


    public static String getBase64(Map map) {
        HashMap<String, Object> hashMap = new HashMap<>();
        String json = new Gson().toJson(map);
        String zhi = "";
        try {
            zhi = AESCrypt.getInstance().encrypt(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return zhi;
    }
}
